package com.androidhive.dashboard;

import android.os.AsyncTask;
import android.os.Bundle;
import androidhive.dashboard.R;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidhive.dashboard.Create_Concept_Activity.CreateNewEmail;

public class Voting_Activity extends ListActivity {

	String login_value = "team b"; //this value needs to come from the application object
	private ProgressDialog pDialog;
	JSONParser jsonParser = new JSONParser();
	EditText inputEmailAddress;
	EditText inputMessage;
	private static final String TAG_SUCCESS = "success";
	final ArrayList<RowModel> list = new ArrayList<RowModel>();

	private static String url_submit_team_vote = "http://i-com.co.ug/ufollo/update_voters_stars.php";
	private static String url_team_ids = "http://i-com.co.ug/ufollo/get_team_ids_for_dee.php";
	
	
	// team names JSONArray
	JSONArray Names = null;
	private static final String TAG_Names = "team_name";
	private static final String TAG_Values = "team_name";
	//static final  ArrayList<String> TeamNames = new ArrayList<String>();

	/** Called when the activity is first created. */
	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		

		for (String s : TeamNames) {
			list.add(new RowModel(s));
		}
		Button Submitrating = new Button(this);
		Submitrating.setText("Submit Ratings");
		Submitrating.setTextColor(getResources().getColor(R.color.whitesmoke));
		Submitrating.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.custom_btn_arsenic));

		getListView().addFooterView(Submitrating);

		setListAdapter(new RatingAdapter(list));
		Submitrating.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				for (RowModel r : list) {
					//Toast.makeText(Voting_Activity.this,
					//		String.valueOf(r.label + " " + r.rating),
					//		Toast.LENGTH_SHORT).show();

					new NetworkActivity().execute();
				}

			}

		});

	}

	private RowModel getModel(int position) {
		return (((RatingAdapter) getListAdapter()).getItem(position));
	}

	class RatingAdapter extends ArrayAdapter<RowModel> {
		RatingAdapter(ArrayList<RowModel> list) {
			super(Voting_Activity.this, R.layout.client_row, list);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			ViewWrapper wrapper;
			RatingBar rate;
			if (row == null) {
				LayoutInflater inflater = getLayoutInflater();
				row = inflater.inflate(R.layout.client_row, parent, false);
				wrapper = new ViewWrapper(row);
				row.setTag(wrapper);
				rate = wrapper.getRatingBar();
				RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
					public void onRatingChanged(RatingBar ratingBar,
							float rating, boolean fromTouch) {
						Integer myPosition = (Integer) ratingBar.getTag();
						RowModel model = getModel(myPosition);
						model.rating = rating;
						LinearLayout parent = (LinearLayout) ratingBar
								.getParent();
						TextView label = (TextView) parent
								.findViewById(R.id.lbl_team);
						label.setText(model.toString());
					}
				};
				rate.setOnRatingBarChangeListener(l);
			} else {
				wrapper = (ViewWrapper) row.getTag();
				rate = wrapper.getRatingBar();
			}

			RowModel model = getModel(position);

			wrapper.getLabel().setText(model.toString());
			rate.setTag(new Integer(position));
			rate.setRating(model.rating);
			return (row);
		}
	}

	class RowModel {
		String label;
		float rating = 0.0f;

		RowModel(String label) {
			this.label = label;
		}

		public String toString() {
			if (rating >= 5.0) {
				return (label);
			}
			return (label);
		}

		public void setRating(float nr) {
			rating = nr;
		}
	}

	static final String[] TeamNames = new String[] { "Team 1", "Team 2",
		"Team 3", "Team 4", "Team 5", "Team 6", "Team 7", "Team 8" };


	/**
	 * Network activity
	 * @author s212226738
	 *
	 */
	class NetworkActivity extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Voting_Activity.this);
			pDialog.setMessage("Sending Message..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}


		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub

			String team_name = login_value;
			//String total_stars = login_value;
			//String team_name = login_value;

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for (RowModel r : list) {
				float rating = r.rating;
				params.add(new BasicNameValuePair("team_name", team_name));
				params.add(new BasicNameValuePair("total_stars", ""+rating));				
			}

			// getting JSON Object
			// Note that create product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(url_submit_team_vote,
					"POST", params);


			return null;
		}
		
		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
		}


	}


	/**
	 * Get Team Names: Returns an array List of team names
	 * @author s212226738
	 *
	 */
	class GetTeamNames extends AsyncTask<String, String, String> {


		@Override
		protected String doInBackground(String... arg0) {

			String team_name = login_value;
		

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("team_name", ""));
			JSONObject json = jsonParser.makeHttpRequest(url_team_ids, "GET", params);

			// check for success tag
			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// products found
					// Getting Array of Products
					Names = json.getJSONArray(TAG_Names);

					// looping through All Products
					for (int i = 0; i < Names.length(); i++) {
						JSONObject c = Names.getJSONObject(i);

						// Storing each json item in variable
						String name = c.getString(TAG_Values);
						//static final  ArrayList<String> TeamNames = new ArrayList<String>();
						//TeamNames.add(name);
						
						//static final String[] TeamNames
	
					}
				} else {
					// no products found
					// Launch Add New product Act
					// // Closing all previous activities
					// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					// startActivity(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}


			return null;
		}
		
		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once done
			pDialog.dismiss();
		}


	}
}